﻿using System;
using System.Collections.Concurrent;
using System.ServiceModel;
using DemoLib.Providers.Shared.Contracts;
using DemoLib.Providers.Shared.Models;

namespace DemoLib.Providers.Service
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
        ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class OutputCacheService : IOutputCacheService
    {
        private readonly ConcurrentDictionary<string, OutputCache> _outputCacheList;   

        public OutputCacheService()
        {
            _outputCacheList = new ConcurrentDictionary<string, OutputCache>();
        }

        public OutputCache Get(string key)
        {
            OutputCache cache;

            if (_outputCacheList.TryGetValue(key, out cache))
            {
                if (cache.Expiry < DateTime.Now)
                {
                    Remove(key);
                }
                else
                {
                    return cache;
                }
            }

            return null;
        }

        public OutputCache AddOrUpdate(OutputCache outputCache)
        {
            return  _outputCacheList.AddOrUpdate(outputCache.Key,
                                         outputCache,
                                         (k, v) =>
                                             {
                                                 v.Expiry = outputCache.Expiry;
                                                 v.CacheObject = v.CacheObject;
                                                 return v;
                                             });
        }

        public void Remove(string key)
        {
            OutputCache cache;
            _outputCacheList.TryRemove(key, out cache);

        }
    }
}
